<template>
  <div class="homework-tracking-container">
    <a-card title="作业跟踪" :bordered="false">
      <div class="header-actions">
        <a-input-search
          v-model="searchText"
          placeholder="搜索作业标题"
          @search="handleSearch"
          style="width: 200px; margin-right: 16px"
        />
        <a-button @click="exportHomeworkData" style="margin-left: 8px">
          <template #icon><export-outlined /></template>
          导出数据
        </a-button>
        <a-button @click="generateAIReport" style="margin-left: 8px">
            <template #icon><robot-outlined /></template>
          AI分析报告
          </a-button>
          </div>
      <a-table
        :columns="columns"
        :data-source="filteredHomeworkList"
        row-key="id"
        :pagination="{ pageSize: 10 }"
        :loading="loading"
      >
        <template #progress="{ record }">
          <a-progress
            :percent="calculateCompletionRate(record)"
            :stroke-color="getProgressColor(record)"
          />
</template>
        <template #status="{ record }">
          <a-tag :color="getStatusColor(record)">
            {{ getStatusText(record) }}
          </a-tag>
        </template>
        <template #action="{ record }">
          <a-space>
            <a-button type="link" @click="viewDetails(record)">查看详情</a-button>
            <a-button type="link" @click="sendReminder(record)">发送提醒</a-button>
            <a-button type="link" danger @click="confirmDelete(record)">
              删除
            </a-button>
          </a-space>
        </template>
      </a-table>
    </a-card>

    <!-- AI Report Modal -->
    <a-modal
      v-model:visible="aiReportVisible"
      title="AI 作业分析报告"
      width="800px"
      :footer="null"
    >
      <div v-if="aiReportLoading" class="loading-container">
        <a-spin tip="AI正在生成报告..." />
      </div>
      <div v-else class="ai-report-content">
        <h3>整体完成情况</h3>
        <p>{{ aiReport.overall }}</p>

        <h3>学生表现分析</h3>
        <p>{{ aiReport.performance }}</p>

        <h3>建议</h3>
        <p>{{ aiReport.suggestions }}</p>

        <div v-if="aiReport.chartData" class="chart-container">
          <h3>完成率趋势</h3>
          <a-echarts :option="aiReport.chartData" style="height: 300px" />
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script>
import { ExportOutlined, RobotOutlined } from '@ant-design/icons-vue'
// import { message, Modal } from 'ant-design-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const columns = [
  {
    title: '作业标题',
    dataIndex: 'title',
    key: 'title',
    sorter: (a, b) => a.title.localeCompare(b.title),
  },
  {
    title: '截止日期',
    dataIndex: 'deadline',
    key: 'deadline',
    sorter: (a, b) => new Date(a.deadline) - new Date(b.deadline),
  },
  {
    title: '提交人数',
    dataIndex: 'submittedCount',
    key: 'submittedCount',
    sorter: (a, b) => a.submittedCount - b.submittedCount,
  },
  {
    title: '未提交人数',
    dataIndex: 'unsubmittedCount',
    key: 'unsubmittedCount',
    sorter: (a, b) => a.unsubmittedCount - b.unsubmittedCount,
  },
  {
    title: '完成率',
    key: 'progress',
    slots: { customRender: 'progress' },
  },
  {
    title: '状态',
    key: 'status',
    slots: { customRender: 'status' },
  },
  {
    title: '操作',
    key: 'action',
    slots: { customRender: 'action' },
  },
]

export default {
  name: 'HomeworkTracking',
  components: {
    ExportOutlined,
    RobotOutlined,
  },
  data() {
    return {
      columns,
      homeworkList: [
        {
          id: 1,
          title: '数学作业 - 二次函数',
          submittedCount: 20,
          unsubmittedCount: 5,
          deadline: '2023-12-15 23:59',
          totalStudents: 25,
        },
        {
          id: 2,
          title: '英语作业 - 阅读理解',
          submittedCount: 18,
          unsubmittedCount: 7,
          deadline: '2023-12-10 23:59',
          totalStudents: 25,
        },
        {
          id: 3,
          title: '物理实验报告',
          submittedCount: 15,
          unsubmittedCount: 10,
          deadline: '2023-12-20 23:59',
          totalStudents: 25,
        },
      ],
      searchText: '',
      loading: false,
      aiReportVisible: false,
      aiReportLoading: false,
      aiReport: {
        overall: '',
        performance: '',
        suggestions: '',
        chartData: null,
      },
    }
      },
  computed: {
    filteredHomeworkList() {
      return this.homeworkList.filter((item) =>
        item.title.toLowerCase().includes(this.searchText.toLowerCase())
      )
    },
  },
  methods: {
    calculateCompletionRate(record) {
      return Math.round(
        (record.submittedCount / (record.submittedCount + record.unsubmittedCount)) * 100
    )},
    getProgressColor(record) {
      const rate = this.calculateCompletionRate(record)
      return rate > 80 ? '#52c41a' : rate > 50 ? '#faad14' : '#f5222d'
    },
    getStatusColor(record) {
      const now = new Date()
      const deadline = new Date(record.deadline)
      return now > deadline ? (record.unsubmittedCount > 0 ? 'red' : 'green') : 'blue'
    },
    getStatusText(record) {
      const now = new Date()
      const deadline = new Date(record.deadline)
      if (now > deadline) {
        return record.unsubmittedCount > 0 ? '已截止(未完成)' : '已截止(全部完成)'
      }
      return '进行中'
    },
    viewDetails(record) {
      this.$router.push(`/homework/details/${record.id}`)
    },
    sendReminder(record) {
      this.loading = true
      // 模拟API调用
      setTimeout(() => {
        this.loading = false
        message.success(`已向${record.unsubmittedCount}名学生发送提醒`)
      }, 1000)
    },
    confirmDelete(record) {
      Modal.confirm({
        title: '确认删除作业?',
        content: `确定要删除作业 "${record.title}" 吗?`,
        okText: '确认',
        cancelText: '取消',
        onOk: () => this.deleteHomework(record),
      })
    },
    deleteHomework(record) {
      this.homeworkList = this.homeworkList.filter((item) => item.id !== record.id)
      message.success('作业删除成功')
    },
    handleSearch() {
      // 搜索功能已在computed属性中实现
    },
    exportHomeworkData() {
      this.loading = true
      // 模拟导出功能
      setTimeout(() => {
        this.loading = false
        message.success('作业数据导出成功')
      }, 1000)
    },
    generateAIReport() {
      this.aiReportVisible = true
      this.aiReportLoading = true

      // 模拟AI分析API调用
      setTimeout(() => {
        this.aiReport = {
          overall: '班级整体作业完成率为72%，略低于平均水平(75%)。数学作业完成率最高(80%)，物理实验报告完成率最低(60%)。',
          performance: '约30%的学生按时完成了所有作业，15%的学生有超过2项作业未提交。张同学、李同学表现突出，王同学需要特别关注。',
          suggestions: '1. 对未完成物理实验报告的学生进行个别辅导\n2. 考虑调整作业难度梯度\n3. 对持续表现不佳的学生安排一对一沟通',
          chartData: {
            tooltip: {
              trigger: 'axis',
            },
            xAxis: {
              type: 'category',
              data: ['数学', '英语', '物理'],
            },
            yAxis: {
              type: 'value',
            },
            series: [
              {
                data: [80, 72, 60],
                type: 'line',
                smooth: true,
              },
            ],
          },
        }
        this.aiReportLoading = false
      }, 2000)
    },
    },
}
</script>

<style scoped>
.homework-tracking-container {
  padding: 24px;
  background: #fff;
}

.header-actions {
  margin-bottom: 16px;
  display: flex;
  align-items: center;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

.ai-report-content {
  max-height: 600px;
  overflow-y: auto;
}

.ai-report-content h3 {
  margin-top: 16px;
  color: #1890ff;
}

.chart-container {
  margin-top: 24px;
}
</style>